package com.want.buss.interfaces.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.jws.WebMethod;
import javax.jws.WebService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.want.buss.interfaces.dto.BankAccountInfoParam;
import com.want.buss.interfaces.dto.DepositMethodParam;
import com.want.buss.interfaces.dto.MoneyCertificatesParam;
import com.want.buss.interfaces.dto.MoneyTypeDetailParam;
import com.want.buss.interfaces.mapper.CustomerDepositMapper;
import com.want.buss.interfaces.po.BankAccountInfo;
import com.want.buss.interfaces.po.DepositMethod;
import com.want.buss.interfaces.po.MoneyCertificates;
import com.want.buss.interfaces.po.MoneyTypeDetail;
import com.want.buss.interfaces.po.OutMsg;
import com.want.buss.interfaces.service.CustomerDepositService;
import com.want.buss.interfaces.util.WebServiceUtil;

@Service
//@WebService
public class CustomerDepositServiceImpl implements CustomerDepositService {
	Logger logger = Logger.getLogger(CustomerDepositServiceImpl.class);  
	@Autowired
	CustomerDepositMapper customerDepositMapper;

	@Transactional
	@WebMethod
	@Override
	public OutMsg createCustomerDeposit(String saveOrCommit, DepositMethodParam depositMethodParam, BankAccountInfoParam bankAccountInfoParam,
			List<MoneyTypeDetailParam> moneyTypeDetailParamList, List<MoneyCertificatesParam> moneyCertificatesParamList) {
		// TODO Auto-generated method stub
		OutMsg outMsg = new OutMsg();
		if (depositMethodParam == null || bankAccountInfoParam == null || moneyTypeDetailParamList == null || moneyCertificatesParamList == null) {
			outMsg.setCode("E");
			outMsg.setText("请检查数据完整性！");
			return outMsg;
		}

		DepositMethod depositMethod = null;
		try {
		
			BigDecimal depositSid = depositMethodParam.getSid();
			String user = depositMethodParam.getUpdateUser();
			String customerId = depositMethodParam.getCustomerId();
			//判断是新增入金还是修改入金
			if (depositSid != null && !"".equals(depositSid)) {
				logger.info(depositMethodParam.getCompanyId() + '-' +depositMethodParam.getCustomerId()+"修改入金单");
				depositMethod = customerDepositMapper.findById(depositSid);
		        depositMethod.setUpdateDate(new Date());
		        depositMethod.setUpdateUser(user);
			} else {
				logger.info(depositSid + "新增入金单");
				depositMethod = new DepositMethod();
				depositMethod.setInputTime(new Date());
				depositMethod.setCreateDate(new Date());
		        depositMethod.setCreateUser(user);
		        depositMethod.setUpdateDate(new Date());
		        depositMethod.setUpdateUser(user);
			}
			
	        depositMethod.setCustomerId(depositMethodParam.getCustomerId());
	        depositMethod.setCustomerName(depositMethodParam.getCustomerName());
	        depositMethod.setCompanyId(depositMethodParam.getCompanyId());
	        depositMethod.setCompanyName(depositMethodParam.getCompanyName());
	        depositMethod.setTotalAmount(depositMethodParam.getTotalAmount());
	        depositMethod.setDepositStatus(depositMethodParam.getDepositStatus());
	        depositMethod.setLoginAccount(depositMethodParam.getLoginAccount());
	
	        
	        if (depositSid != null && !"".equals(depositSid) ) {
	        	logger.info("-------修改入金单开始-------");
				customerDepositMapper.update(depositMethod);
				//删除账户信息和金额类别明细和打款凭证
				customerDepositMapper.deleteBankAccountInfoByDepositSid(depositMethod.getSid());
				customerDepositMapper.deleteMoneyTypeDetailByDepositSid(depositMethod.getSid());
				customerDepositMapper.deleteMoneyCertificatesByDepositSid(depositMethod.getSid());
			} else {
				logger.info("-------新增入金单开始-------");
	        	customerDepositMapper.create(depositMethod);
			} 
	        
	        // 银行账户信息
	        BankAccountInfo bankAccountInfo = new BankAccountInfo();
	        bankAccountInfo.setHouseholder(bankAccountInfoParam.getHouseholder());
	        bankAccountInfo.setBankAccount(bankAccountInfoParam.getBankAccount());
	        bankAccountInfo.setBankName(bankAccountInfoParam.getBankName());
	        bankAccountInfo.setBankSeriesNumber(bankAccountInfoParam.getBankSeriesNumber());
	        bankAccountInfo.setIsCustomerSame(bankAccountInfoParam.getIsCustomerSame());
	        bankAccountInfo.setCustomerBankName(bankAccountInfoParam.getCustomerBankName());
	        bankAccountInfo.setCustomerBankAccount(bankAccountInfoParam.getCustomerBankAccount());
	        bankAccountInfo.setCustomerBankNo(bankAccountInfoParam.getCustomerBankNo());
	        bankAccountInfo.setCustomerHouseholder(bankAccountInfoParam.getCustomerHouseholder());
	        bankAccountInfo.setCreateDate(new Date());
	        bankAccountInfo.setCreateUser(user);
	        bankAccountInfo.setDepositSid(depositMethod.getSid());
	        
	        //查询银行流水单号查询
	        List<BankAccountInfo> bankAccountList = customerDepositMapper.getBankAccountInfoByBankSeriesNumber(bankAccountInfoParam.getBankSeriesNumber(), depositMethod.getSid());
	        if (bankAccountList != null && bankAccountList.size() == 0) {
	        	customerDepositMapper.insertBankAccountInfo(bankAccountInfo);
	        }
	        
	        //金额类别明细
	        if (moneyTypeDetailParamList.size() > 0) {
	        	List<MoneyTypeDetail> moneyTypeDetailList = new ArrayList<MoneyTypeDetail>();
	        	
	        	//查询全部通知人员
	        	List<Map<String, Object>> empList = customerDepositMapper.queryCustomerNoticeEmp(customerId);
	        	for (int i = 0; i < moneyTypeDetailParamList.size(); i++) {
	        		MoneyTypeDetail moneytypeDetail = new MoneyTypeDetail();
	        		moneytypeDetail.setDepositSid(depositMethod.getSid());
	        		moneytypeDetail.setMoneyType(moneyTypeDetailParamList.get(i).getMoneyType());
	        		moneytypeDetail.setAmount(moneyTypeDetailParamList.get(i).getAmount());
	        		moneytypeDetail.setMarginAmountType(moneyTypeDetailParamList.get(i).getMarginAmountType());
	        		moneytypeDetail.setChannelId(moneyTypeDetailParamList.get(i).getChannelId());
	        		moneytypeDetail.setOrderNo(moneyTypeDetailParamList.get(i).getOrderNo());
	        		moneytypeDetail.setOrderNoDesc(moneyTypeDetailParamList.get(i).getOrderNoDesc());
	        		moneytypeDetail.setSpecialFundNo(moneyTypeDetailParamList.get(i).getSpecialFundNo());
	        		moneytypeDetail.setSpecialFundName(moneyTypeDetailParamList.get(i).getSpecialFundName());
	        		moneytypeDetail.setSpecialFundMoney(moneyTypeDetailParamList.get(i).getSpecialFundMoney());
	
	        		// 资深主任（015）
	                String noticeDirectorEmpId = "";
	                // 业管（008）
	                String noticeBussEmpId = "";
	                
	                for (int j = 0; j < empList.size(); j++) {
	                    Map<String, Object> map = empList.get(j);
	                    
	                    //拼接业管编号
	                    if ("008".equals(map.get("POS_TYPE_ID"))) {
	                        noticeBussEmpId +=    ("".equals(noticeBussEmpId) ? "" : ",") + map.get("EMP_ID");
	                    }
	                    // 如果信控范围不为空，则取对应渠道的资深主任
	                    else if (!"".equals(moneyTypeDetailParamList.get(i).getChannelId()) && moneyTypeDetailParamList.get(i).getChannelId().equals(map.get("CHANNEL_ID")) && "015".equals(map.get("POS_TYPE_ID"))) {
	                        noticeDirectorEmpId +=    ("".equals(noticeDirectorEmpId) ? "" : ",") + map.get("EMP_ID");
	                    }
	                }
	
	        		moneytypeDetail.setNoticeDirectorEmpId(noticeDirectorEmpId);
	        		moneytypeDetail.setNoticeBussEmpId(noticeBussEmpId);
	        		moneytypeDetail.setCreateDate(new Date());
	        		moneytypeDetail.setCreateUser(user);
	        		
	        		moneyTypeDetailList.add(moneytypeDetail);
	        	}
	        	
	        	customerDepositMapper.insertMoneyTypeDetail(moneyTypeDetailList);
	        }
	        	
	        //文件信息
	        MoneyCertificates moneyCertifactes = null;
	        List<MoneyCertificates> moneyCertificatesList = new ArrayList<MoneyCertificates>();
	        for (int z = 0; z < moneyCertificatesParamList.size(); z++) {
	        	moneyCertifactes = new MoneyCertificates();
	        	moneyCertifactes.setDepositSid(depositMethod.getSid());
	        	moneyCertifactes.setCertificatesName(moneyCertificatesParamList.get(z).getCertificatesName());
	        	moneyCertifactes.setFilesize(moneyCertificatesParamList.get(z).getFilesize());
	        	moneyCertifactes.setPath(moneyCertificatesParamList.get(z).getPath());
	        	moneyCertifactes.setCreateDate(new Date());
	        	moneyCertifactes.setCreateUser(user);
	        		
	        	moneyCertificatesList.add(moneyCertifactes);
	        }
	        	
	        customerDepositMapper.insertMoneyCertificates(moneyCertificatesList);

	    	// 如果提交入金单，则调用webservice接口
	        if ("commit".equals(saveOrCommit)) {
	      	  	logger.info("BPM 抛转(入金)");
	            // 查询入金单
	            DepositMethod depositMethodInfo = customerDepositMapper.findById(depositMethod.getSid());
	           
	            // 查询银行账户信息
	            List<BankAccountInfo> bankAccountInfos = customerDepositMapper.getBankAccountInfoByBankSeriesNumber(bankAccountInfoParam.getBankSeriesNumber(), depositMethod.getSid());
	            
	            // 查询入金明细
	            List<Map<String, Object>> moneyTypeDetailList2 =  customerDepositMapper.getMoneyTypeDetailByDepositSid(depositMethod.getSid());
	
	            // 查询入金凭证
	            List<Map<String, Object>> moneyCertificatesList2 = customerDepositMapper.getMoneyCertificatesByDepositSid(depositMethod.getSid());
	
	            // 发送资料并接收返回值
	            Map<String, Object> retuenMap = WebServiceUtil.sendDepositInfo(depositMethodInfo, bankAccountInfos.get(0), moneyTypeDetailList2, moneyCertificatesList2);
	            
	            // 如果回传结果为“S”,则更新审核结果为审核中
	            if("S".equals(retuenMap.get("code") != null ? retuenMap.get("code").toString() : "")) {
	              depositMethod.setCheckStatus("1");
	            }
	            
	            // 接收message
	            String message = retuenMap.get("message") != null ? retuenMap.get("message").toString() : null;
	            
	            depositMethod.setCode(retuenMap.get("code") != null ? retuenMap.get("code").toString() : null);
	            depositMethod.setMessage(message);
	            
	            // 如果message中包含BPM单号，则更新该单号
	            depositMethod.setBpmId(message != null ? (message.split(":").length > 1 ? message.split(":")[0] : null) : null);
	
	            customerDepositMapper.update(depositMethod); 	
	    	
	    	
	        }
	        outMsg.setCode("S");
	        outMsg.setText("");
	        
		} catch (Exception ex) {
			outMsg.setCode("E");
	        outMsg.setText("逻辑处理出现错误");
	        ex.printStackTrace();
		} 

        return outMsg;
    }
	
}

